﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using DBconnection;
using RulesCore;
using SocketConnections;
using AddRule;
using simulation;

namespace Main_Form
{
    public partial class MainApp : Form
    {
        public MainApp()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StartUp strt = new StartUp(Start);
            //Thread start=new Thread(new ThreadStart(Start));
            this.Invoke(strt);
            
        }
        delegate void StartUp();
        
        private void Start()
        {
            btStart.Enabled = false;
            btSync.Enabled = false;
            bt_AddRule.Enabled = false;

            DateTime time = DateTime.Now;
            
                txtBox.Text = (time + " " + "Starting the system...");
                Thread.Sleep(2000);
                txtBox.AppendText(Environment.NewLine);
                time = DateTime.Now;
                txtBox.AppendText(time + " " + "Check if DB Exist...");
                Thread.Sleep(2000);
            
            try
            {
                DB.OpenConnection();
                txtBox.AppendText(Environment.NewLine);
                time = DateTime.Now;
                txtBox.AppendText(time + " " + "DB Exist! Continue....");
                Thread.Sleep(2000);
                DB.CloseConnection();
            }
            catch
            {
                txtBox.AppendText(Environment.NewLine);
                time = DateTime.Now;
                txtBox.AppendText(time + " " + "DB Not exist! Creating DB....");
                Thread.Sleep(2000);
                DB.Create();
                txtBox.AppendText(Environment.NewLine);
                time = DateTime.Now;
                txtBox.AppendText(time + " " + "DB Created succesfully! ....");
                Thread.Sleep(2000);
            }
            txtBox.AppendText(Environment.NewLine);
            Thread.Sleep(2000);
            time = DateTime.Now;
            txtBox.AppendText(time + " " + "For Start Click 'Hathel' ...");

            btSync.Enabled = true;

            if (DB.CountOfClasses() > 0)
            {
                bt_AddRule.Enabled = true;
                btStart.Enabled = true;
            }
            else
            {
                bt_AddRule.Enabled=false;
                btStart.Enabled = false;
            }
        }

        private void btSync_Click(object sender, EventArgs e)
        {
            txtBox.AppendText(Environment.NewLine);
            DateTime time = DateTime.Now;
            txtBox.AppendText(time + " " + "<< Sync Start! >>");
            Create();
            Thread runSystem = new Thread(new ThreadStart(PrSocket.Sync));
            runSystem.Start();
            runSystem.Join();
            if (runSystem.IsAlive == false)
            {
                HideConsoleWindow();
                Destroy();
                txtBox.AppendText(Environment.NewLine);
                time = DateTime.Now;
                txtBox.AppendText(time + " " + "<< Sync Ends! >>");
            }

            if (DB.CountOfClasses() > 0)
            {
                bt_AddRule.Enabled = true;
                btStart.Enabled = true;
            }
            else
            {
                bt_AddRule.Enabled = false;
                btStart.Enabled = false;
            }
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            Create();
            SIM.Start(); // Init the Classes dictionary
            PrSocket.Input(); // Open the socket and waiting for connection and commands


            //TODO:GET RULES AND INSERT THEM INTO RULES ARRAY
            //TODO:Socket.Input()
            



           // string[]tst=DB.GettingRule_Text("3");
           // RUCore.BuildRule(tst);
           // //RUCore ru = new RUCore(tst);
           //// ru.ChekRule();
        }



        /*For Console Window*/
        public static int Create()
        {
            if (AllocConsole())
                return 0;
            else
                return Marshal.GetLastWin32Error();
        }
        
        private void SetTextboxText(string txt, bool ToAppend)
        {
            if (ToAppend)
                txtBox.AppendText(txt);
            else
                txtBox.Text = txt;
        }

        public static int Destroy()
        {
            if (FreeConsole())
                return 0;
            else
                return Marshal.GetLastWin32Error();
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();


        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool FreeConsole();

        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_HIDE = 0x0;
        const int SW_SHOW = 0x5;

        public static void HideConsoleWindow()
        {
            var handle = GetConsoleWindow();
            ShowWindow(handle, SW_HIDE);

        }

        private void bt_AddRule_Click(object sender, EventArgs e)
        {
            AddRuleForm arf = new AddRuleForm();
            arf.Show();
        }
        /*For Console Window*/
    }
}
